<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form
          ref="searchForm"
          :model="searchForm"
          inline
          :label-width="75"
          class="search-form"
        >
          <Form-item label="审核状态" prop="name">
            <Select v-model="searchForm.auditStatus" placeholder="请选择" clearable style="width: 200px">
              <Option value="0">待审核</Option>
              <Option value="1">审核通过</Option>
              <Option value="2">已驳回</Option>
            </Select>
          </Form-item>
          <Form-item label="还款状态">
            <Select v-model="searchForm.repaymentStatus" placeholder="请选择" clearable style="width: 200px">
              <Option value="0">未还</Option>
              <Option value="1">已还</Option>
            </Select>
          </Form-item>
          <Button
            @click="handleSearch"
            class="search-btn"
            type="primary"
            icon="ios-search"
          >搜索</Button
          >
          <Button style="margin-left: 10px"
                  type="primary"
                  @click="handleReset">重置</Button>
        </Form>
      </Row>
            <Row class="operation padding-row">
              <Button @click="addCredit" type="primary">添加授信</Button>
            </Row>
      <Table
        :loading="loading"
        border
        :columns="columns"
        class="mt_10"
        :data="data"
        ref="table"
      ></Table>
      <Row type="flex" justify="end" class="mt_10">
        <Page
          :current="searchForm.pageNumber"
          :total="total"
          :page-size="searchForm.pageSize"
          @on-change="changePage"
          @on-page-size-change="changePageSize"
          :page-size-opts="[10, 20, 50, 100]"
          size="small"
          show-total
          show-elevator
          show-sizer
        ></Page>
      </Row>
    </Card>
    <!-- 新增/编辑 -->
    <!-- 	<Modal v-model="detailFlag" :title="title" :mask-closable="false">
			<div>
				<Form ref="ruleValidate" :rules="ruleValidate" :model="form" :label-width="100">
					<FormItem label="商家名称" prop="name">
						<div class="item">
							<Input disabled v-model="form.name" />
							<Button @click="handleselectMember()">选择商家</Button>
						</div>
					</FormItem>
					<FormItem label="授信额度" prop="creditLine">
						<Input v-model="form.creditLine" type="number" />
					</FormItem>
					<FormItem label="授信周期" prop="creditPeriod">
						<Input v-model="form.creditPeriod" />
					</FormItem>
					<FormItem label="授信日期" prop="creditDate">
						<DatePicker v-model="form.creditDate" format="yyyy-MM-dd" type="date" style="width: 200px">
						</DatePicker>
					</FormItem>
					<FormItem label="授信状态" prop="creditStatus">
						<i-switch size="large" v-model="form.creditStatus">
							<span slot="open">启用</span>
							<span slot="close">冻结</span>
						</i-switch>
					</FormItem>
					<FormItem label="冻结原因" v-show="!form.creditStatus" prop="creditStatus">
						<Input v-model="form.freezeReason" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" />
					</FormItem>
					<FormItem>
						<Button type="primary" @click="handleSubmit('formValidate')">确定</Button>
						<Button @click="handleCancel('formValidate')" style="margin-left: 8px">取消</Button>
					</FormItem>
				</Form>
			</div>
		</Modal> -->

    <Modal
      :title="title"
      v-model="detailFlag"
      :mask-closable="false"
      :width="500"
      :styles="{ top: '30px' }"
    >
      <Form
        ref="ruleValidate"
        :model="form"
        :rules="ruleValidate"
        :label-width="100"
      >
        <FormItem label="商家名称" prop="name">
          <div class="item">
            <Input v-model="form.name" readonly />
            <!--            <Button @click="handleselectMember()">选择商家</Button>-->
          </div>
        </FormItem>
        <FormItem label="授信额度" prop="creditLine">
          <Input v-model="form.creditLine" type="number" />
        </FormItem>
        <!--        <FormItem label="授信周期" prop="creditPeriod">
                  <Input v-model="form.creditPeriod" readonly />
                </FormItem>-->
        <FormItem label="到期时间" prop="expiryDate">
          <DatePicker
            v-model="form.expiryDate"
            format="yyyy-MM-dd"
            type="date"
            style="width: 200px"
          >
          </DatePicker>
        </FormItem>
        <FormItem
          label="冻结原因"
          v-show="!form.creditStatus"
          prop="creditStatus"
        >
          <Input
            v-model="form.freezeReason"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 5 }"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          type="text"
          @click="handleCancel('formValidate')"
          style="margin-left: 8px"
        >取消</Button
        >
        <Button type="primary" @click="handleSubmit('formValidate')"
        >确定</Button
        >
      </div>
    </Modal>
    <!-- 选择商家弹框 -->
    <Modal
      title="还款"
      v-model="repaymentModalFlag"
      @on-cancel="handleCancelSeller"
      :width="500"
      :styles="{ top: '30px' }"
    >
      <Form
        ref="ruleValidate"
        :label-width="100"
      >
        <FormItem label="还款金额">
          <Input v-model="money" readonly style="width: 260px" />
          <div> {{warning}}</div>
        </FormItem>

      </Form>
      <div slot="footer">
        <Button
          type="text"
          @click="handleCancelRepayment('formValidate')"
          style="margin-left: 8px"
        >取消</Button
        >
        <Button type="primary" @click="handleSubmitRepayment('formValidate')"
        >确定</Button
        >
      </div>
    </Modal>
    <Modal
      :title="repaymentTitle"
      v-model="repaymentFlag"
      :mask-closable="false"
      :width="500"
      :styles="{ top: '30px' }"
      footer-hide
    >
      <Form
        ref="ruleValidate"
        :model="form"
        :label-width="100"
      >
        <FormItem label="充值钱包">
            <Input v-model="price.rechargeMoney" readonly style="width: 260px" />
            <Button @click="handleRepayment('RECHARGE',price.rechargeMoney)" :disabled="price.rechargeMoney<money" style="margin-left: 10px">还款</Button>
        </FormItem>
        <FormItem label="推广钱包">
          <Input v-model="price.promoteMoney" readonly style="width: 260px" />
          <Button @click="handleRepayment('PROMOTE',price.promoteMoney)" :disabled="price.promoteMoney<money" style="margin-left: 10px">还款</Button>
        </FormItem>
        <FormItem label="销售钱包">
          <Input v-model="price.saleMoney" readonly style="width: 260px" />
          <Button @click="handleRepayment('SALE',price.saleMoney)" :disabled="price.saleMoney<money" style="margin-left: 10px">还款</Button>
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<script>
import {
  getCreditList,
  addCredit,
  examineCredit,
  creditRepay,
} from "@/api/credit.js";
import Cookies from "js-cookie";
import {repayment} from "../../api/credit";

export default {
  name: "credit-manager",
  data() {
    return {
      money:'',// 还款金额
      loading: true, // 表单加载状态
      loadingModal: true, // 表单加载状态
      detailFlag: false,
      title: "新增", //弹窗title
      repaymentModalFlag: false, // 还款页面
      searchForm: {
        // 请求参数
        pageNumber: 1,
        pageSize: 10,
        order: "desc",
        name: "",
        repaymentStatus: ""
      },
      searchFormModal: {
        // 请求参数
        pageNumber: 1,
        pageSize: 10,
        order: "desc",
        storeName: "",
      },
      form: {
        memberId: "",
        name: "", //商家名称
        // nameType: "",
        //contactInformation: "",
        userAddress: "",
        creditLine: "",
        creditStatus: true,
        creditPeriod: "",
        creditDate: "",
        freezeReason: "", //冻结原因
        expiryDate: "", //到期时间
        repaymentDate: "", // 还款时间
      },
      EditObj: null,
      auditStatus: 0,
      columns: [
        {
          title: "商家名称",
          key: "name",
          tooltip: true,
        },
        // {
        //   title: "商家类型",
        //   key: "nameType",
        // },
        {
          title: "授信额度",
          align: "left",
          key: "creditLine",
        },
        {
          title: "授信日期",
          align: "left",
          key: "creditDate",
          render: (h, params) => {
            return h("div", {},
              params.row.creditDate == null
                ? ""
                : params.row.creditDate.split(" ")[0]
            );
          },
        },
        {
          title: "审核状态",
          align: "left",
          render: (h, params) => {
            return h(
              "div",
              {},
              params.row.auditStatus == 1
                ? "审核通过"
                : params.row.auditStatus == 2
                ? "驳回"
                : "待审核"
            );
          },
        },
        {
          title: "还款状态",
          align: "left",
          key: "repaymentStatus",
          render: (h, params) => {
            return h(
              "div",
              {}, params.row.repaymentStatus == 1
                ? "已还"
                : "未还"
            );
          },
        },
        {
          title: "到期时间",
          align: "left",
          key: "expiryDate",
          render: (h, params) => {
            return h("div", {},
              params.row.expiryDate == null
                ? ""
                : params.row.expiryDate.split(" ")[0]
              );
          },
        },
        {
          title: "还款时间",
          align: "left",
          key: "repaymentDate",
          render: (h, params) => {
            return h("div", {},
              params.row.repaymentDate == null
                ? ""
                : params.row.repaymentDate.split(" ")[0]
            );
          },
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 200,
          fixed: "right",
          render: (h, params) => {
            if(params.row.repaymentStatus != 1){
              return h(
                "div",
                {
                  style: {
                    display: "flex",
                    justifyContent: "center",
                  },
                },
                [
                  h(
                    "Button",
                    {
                      props: {
                        type: "info",
                        size: "small",
                      },
                      style: {
                        marginRight: "5px",
                      },
                      on: {
                        click: () => {
                          this.getRepayment(params.row.id, params.row.memberId, params.row.creditLine);
                        },
                      },
                    },
                    "还款"
                  ),
                ]
              );
            }
          },
        },
      ],
      data: [], // 表单数据
      total: 0, // 表单数据总数
      columnsModal: [
        {
          title: "商家名称",
          key: "storeName",
          tooltip: true,
        },
        // {
        //   title: "商家类型",
        //   key: "nameType",
        // },
        {
          title: "商家联系信息",
          key: "mobile",
        },
        {
          title: "商家地址",
          align: "left",
          key: "storeAddressDetail",
        },
        {
          title: "操作",
          key: "action",
          align: "center",
          width: 200,
          fixed: "right",
          render: (h, params) => {
            return h(
              "div",
              {
                style: {
                  display: "flex",
                  justifyContent: "center",
                },
              },
              [
                h(
                  "Button",
                  {
                    props: {
                      size: "small",
                      type:
                        this.selectedObj.id == params.row.id
                          ? "primary"
                          : "default",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.callbackMember(params.row, params.index);
                      },
                    },
                  },
                  this.selectedObj.id == params.row.id ? "已选择" : "选择"
                ),
              ]
            );
          },
        },
      ],
      dataModal: [], // 表单数据
      totalModal: 0, // 表单数据总数
      selectMember: [],
      selectedObj: {},
      ruleValidate: {
        name: [
          {
            required: true,
            message: "请输入商家名称",
            trigger: ["blur", "change"],
          },
        ],
        creditLine: [
          {
            required: true,
            message: "请输入授信额度",
          },
        ],
        expiryDate: [
          {
            required: true,
            message: ["请选择到期时间", "change"],
          },
        ],
      },
      repaymentFlag: false,
      repaymentTitle: "还款",
      repaymentId : '', // 还款id
      memberId : '', // 会员id
      price: '', // 还款金额
      owner: '', // 钱包类型
      warning: '',
      warningStatus : false
    };
  },
  methods: {
    dateFtt(fmt, date) {
      if (date) {
        //author: meizz
        var o = {
          "M+": date.getMonth() + 1, //月份
          "d+": date.getDate(), //日
          "h+": date.getHours(), //小时
          "m+": date.getMinutes(), //分
          "s+": date.getSeconds(), //秒
          "q+": Math.floor((date.getMonth() + 3) / 3), //季度
          S: date.getMilliseconds(), //毫秒
        };
        if (/(y+)/.test(fmt))
          fmt = fmt.replace(
            RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length)
          );
        for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(
              RegExp.$1,
              RegExp.$1.length == 1
                ? o[k]
                : ("00" + o[k]).substr(("" + o[k]).length)
            );
        return fmt;
      }
    },
    // 分页 改变页码
    changePageModal(v) {
      this.searchFormModal.pageNumber = v;
      this.getDataModal();
    },
    // 分页 改变页数
    changePageSizeModal(v) {
      this.searchFormModal.pageSize = v;
      this.searchFormModal.pageNumber = 1;
      this.getDataModal();
    },
    // 选择会员的回调
    callbackMember(val) {
      this.selectedObj = val;
      this.form.memberId = val.memberId; //商家名称
      this.form.name = val.storeName; //商家名称
      // this.form.nameType = val.nameType; //商家类型
      // this.form.contactInformation = val.mobile; //商家联系方式
      this.form.userAddress = val.storeAddressDetail; //商家地址
    },
    //还款
    handleRepayment(owner, price) {
      if (price> this.money){
        this.warning = ''
        this.warningStatus = true
        this.repaymentFlag = !this.repaymentFlag
      }else{
        this.warning = '该钱包的金额小于授信额度';
        this.warningStatus = false
      }
      this.owner = owner
      this.repaymentModalFlag = true;
    },
    // 分页 改变页码
    changePage(v) {
      this.searchForm.pageNumber = v;
      this.getData();
    },
    // 分页 改变页数
    changePageSize(v) {
      this.searchForm.pageSize = v;
      this.searchForm.pageNumber = 1;
      this.getData();
    },
    // 搜索
    handleSearch() {
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.getData();
    },
    handleReset(){
      this.searchForm.pageNumber = 1;
      this.searchForm.pageSize = 10;
      this.searchForm.auditStatus = ""
      this.searchForm.repaymentStatus = ""
      this.getData();
    },
    //查询授信列表
    getData() {
      getCreditList(this.searchForm).then((res) => {
        if (res.result.records) {
          this.loading = false;
          this.data = res.result.records;
          this.total = res.result.total;
        }
      });
    },
    // 新增
    addCredit() {
      this.detailFlag = true;
      this.EditObj = {};
      this.form.name = JSON.parse(Cookies.get('userInfoSeller')).storeName
    },
    getRepayment(id, memberId, creditLine){
      this.repaymentId = id
      this.memberId = memberId
      this.money = creditLine
      repayment().then((res) => {
        if(res.success){
          this.price = res.result
          this.repaymentFlag = true
        }
      });
    },
    //编辑
    edit(row) {
      this.detailFlag = true;
      this.auditStatus = row.auditStatus
      this.EditObj = {
        ...row,
      };
      this.form = {
        ...this.EditObj,
      };
      if (!this.form.freezeReason) {
        this.form.freezeReason = "";
      }
      if (this.EditObj.creditStatus == "0") {
        this.$set(this.form, "creditStatus", false);
      } else {
        this.$set(this.form, "creditStatus", true);
      }
      this.title = "审核";
      // this.$router.push({ name: "member-detail", query: { id: row.id } });
    },
    // 提交事件
    handleSubmit() {
      console.log("提交");
      let params = {
        memberId: this.form.memberId, //商家id
        name: this.form.name, //商家名称
        creditLine: this.form.creditLine,
        expiryDate: this.dateFtt("yyyy-MM-dd",this.form.expiryDate),
      };
      this.$refs.ruleValidate.validate((valid) => {
        if (valid) {
          if (this.EditObj && this.EditObj.id) {
            examineCredit(this.EditObj.id, params).then((res) => {
              if (res.code == 200) {
                this.$Message.success("修改成功！");
                this.form = {
                  memberId: "",
                  name: "", //商家名称
                  // nameType: "",
                  // contactInformation: "",
                  userAddress: "",
                  creditLine: "",
                  creditStatus: true,
                  creditPeriod: "",
                  creditDate: "",
                };
                this.EditObj = {};
                this.selectedObj = {};
                this.title = "新增";
                this.$refs.ruleValidate.resetFields();
                this.getData();
                this.detailFlag = !this.detailFlag;
              } else {
                this.$Message.error("修改失败！");
              }
            });
          } else {
            addCredit(params).then((res) => {
              if (res.code == 200) {
                this.detailFlag = !this.detailFlag;
                this.$Message.success("添加成功！");
                this.form = {
                  memberId: "",
                  name: "", //商家名称
                  // nameType: "",
                  // contactInformation: "",
                  userAddress: "",
                  creditLine: "",
                  creditStatus: true,
                  creditPeriod: "",
                  creditDate: "",
                };
                this.EditObj = {};
                this.selectedObj = {};
                this.title = "新增";
                this.$refs.ruleValidate.resetFields();
                this.getData();
              } else {
                this.$Message.error("添加失败！");
              }
            });
          }
        }
      });
    },
    // 取消事件
    handleCancel() {
      this.form = {
        memberId: "",
        name: "", //商家名称
        // nameType: "",
        // contactInformation: "",
        userAddress: "",
        creditLine: "",
        creditStatus: true,
        creditPeriod: "",
        creditDate: "",
      };
      this.detailFlag = !this.detailFlag;
      this.EditObj = {};
      this.selectedObj = {};
      this.title = "新增";
      this.$refs.ruleValidate.resetFields();
    },
    // 选择商家弹框取消按钮
    handleCancelSeller() {
      this.selectedObj = {};
      this.form.memberId = "";
      this.form.name = ""; //商家名称
    },
    handleSubmitRepayment(){
      let params = {
        memberId: this.memberId,
        creditLine: this.money, //还款金额
        repaymentDate: this.dateFtt("yyyy-MM-dd",new Date()),
        owner: this.owner // 钱包类型
      };
        if (this.warningStatus) {
          creditRepay(this.repaymentId, params).then((res) => {
            if (res.code == 200) {
              this.$Message.success("还款成功！");
              this.$refs.ruleValidate.resetFields();
              this.repaymentModalFlag = !this.repaymentModalFlag;
              this.getData();
            } else {
              this.$Message.error("还款失败！");
            }
          });
        }else {
          this.$Message.warning(this.warning);
        }
    },
    handleCancelRepayment(){
      this.repaymentModalFlag != this.repaymentModalFlag
      this.repaymentFlag = true
    }
  },
  mounted() {
    this.getData();
  },
};
</script>
<style lang="scss" scoped>
/deep/ .ivu-table-wrapper {
  width: 100%;
}

/deep/ .ivu-card {
  width: 100%;
}

.face {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.item {
  width: 350px !important;
  display: flex;

  > * {
    margin: 0 4px;
  }
}
</style>
